package learner;

import java.util.List;

import learner.Pattern;
import learner.dtw.DTWMatrix;
import learner.hmm.Movement;
import learner.hmm.MovementVector;


public class DTWCostCalculator {

	public double calculateCost(Pattern pattern, Pattern givenPattern) {
		Movement firstPatternMoves = new Movement(pattern);
		Movement otherPatternMoves = new Movement(givenPattern);
		List<MovementVector> firstPoints = firstPatternMoves.getMovementVectors();
		List<MovementVector> otherPoints = otherPatternMoves.getMovementVectors();
		int m =firstPoints.size()+1;
		int n =otherPoints.size()+1;
		DTWMatrix dtwMatrix = new DTWMatrix(m, n);
		dtwMatrix.setEntry(0, 0, 0);
		for(int i = 1;i<n;i++){
			try{
			dtwMatrix.setEntry(0, i, Double.MAX_VALUE);
			}
			catch(Exception e){
				System.out.println("index: "+ i);
			}
		}
		for(int i =1;i<m;i++){
			dtwMatrix.setEntry(i, 0, Double.MAX_VALUE);
		}
		double cost;
		for(int i=1;i<m;i++){
			for(int j=1;j<n;j++){
				cost= getDistanceBetween(firstPoints.get(i-1),otherPoints.get(j-1));
				dtwMatrix.setEntry(i, j, cost + Math.min(dtwMatrix.getEntry(i-1,j), //insertion
						Math.min(dtwMatrix.getEntry(i, j-1),						//deletion
						dtwMatrix.getEntry(i-1, j-1))));							//match
			}
		}
		return dtwMatrix.getEntry(m-1, n-1);
	}
	
	private double getDistanceBetween(MovementVector move1,MovementVector move2){
		double xDiff= move1.getX()-move2.getX();
		double yDiff= move1.getY()-move2.getY();
		double euclidDist = Math.sqrt(xDiff*xDiff+yDiff*yDiff);			
		return euclidDist;
	}
}